iT邦幫忙

7

利用 GeoIP 列出某地區的所有IP網段

  • 分享至 

  • xImage
  •  

如何查詢地區性的所有IP網段 ? 這問題中,
主要是為解決如何擋某地區IP,
一般來說只要利用 GeoIP 的 資料檔及各程式的 API 來去做查詢,
就是最好的解決之道。

至於「如何列出某地區的所有IP網段」這問題,
雖然實務上的應用意義不大,
但的確蠻好奇怎麼找出來,
總算試出了怎麼從 GeoIP 的資料檔抓出來。
抓取原始資料
前往 http://www.maxmind.com/app/geolitecity 抓取
GeoLite City CSV Format
解開後裡面有:GeoLiteCity-Blocks.csv GeoLiteCity-Location.csv 兩檔。
http://www.maxmind.com/app/csv有說明各欄位的作用。
以抓取台灣IP為例:
在 GeoLiteCity-Location.csv
locId,country,region,city,postalCode,latitude,longitude,metroCode,areaCode
105645,"CN","30","Taiwan","",22.8167,111.6333,,
可知台灣的LocId是 105645
然後 用該碼查詢 哪些IP 範圍屬於 105645

egrep \"105645\" GeoLiteCity-Blocks.csv > tw.txt
# 欄位分別為:
# startIpNum,endIpNum,locId
"1019108336","1019108339","105645"
"1019111992","1019111999","105645"
"1019162952","1019162959","105645"
"1032003320","1032003327","105645"
"3663831056","3663831071","105645"
"3663832512","3663832543","105645"
"3663832800","3663832815","105645"
"3663836032","3663836047","105645"
"3663836608","3663836623","105645"
"3663837136","3663837151","105645"
"3663837408","3663837423","105645"
"3663837504","3663837519","105645"

轉換樣式
1019108336代表什麼,用 ping 就看出來了:

$ ping 1019108336
PING 1019108336 (60.190.91.240) 56(84) bytes of data.

參考 <http://en.kioskea.net/faq/945-converting-a-32-bit-integer-into-ip >
一文的範例,
利用 perl 的簡單語法來轉換 tw.txt 裡的 ip 樣式:

# 編輯本檔為 32bit2ip.pl
$file = $ARGV[0];
sub toip {
 $bit32 = @_[0];
# $result = $bit32>>24,"." + $bit32<<8>>24,".",$bit32<<16>>24,".",$bit32<<24>>24;
 $a = $bit32>>24;
 $b = $bit32<<8>>24;
 $c = $bit32<<16>>24;
 $d = $bit32<<24>>24;
 return "$a.$b.$c.$d";
}
open(F,"./$ARGV[0]");
while(<F>) {
chomp;
$_ =~ s/"//g;
my($startIpNum,$endIpNum,$locId) = split(',',$_);
#print "$startIpNum\n";
$s = &toip($startIpNum);
$e = &toip($endIpNum);
print "$s-$e\n";
}
close F;

執行 perl 32bit2ip.pl tw.txt 獲得以下結果:

60.190.91.240-60.190.91.243
60.190.106.56-60.190.106.63
60.191.49.72-60.191.49.79
61.131.30.248-61.131.30.255
218.97.160.16-218.97.160.31
218.97.165.192-218.97.165.223
218.97.166.224-218.97.166.239
218.97.179.128-218.97.179.143
218.97.181.192-218.97.181.207
218.97.183.208-218.97.183.223
218.97.184.224-218.97.184.239
218.97.185.64-218.97.185.79

台灣哪有那麼少?
其實應用 Taipei 來找,代號應是 21248及106214,

21248,"TW","03","Taipei","",25.0392,121.5250,,
105628,"TW","03","Taipeihsien","",25.0392,121.5250,,
106214,"CN","07","Taipei","",24.9853,118.6453,,

在 Block 上就有 10211及5 行了…
台北縣也有19行。
所以要把一個區域的IP找出,要把可能的地區名稱都考慮進來。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言